<?php
/* Script is meant for sending new message to specific user.
   
   GET parameters:
      - session_id
      - receiver
      - message
      
   Return values:
      - NONE
      
*/

require_once './common/header.php';

// Get mandatory parameters
$session_id = $_GET['session_id'];
$receiver = $_GET['receiver'];
$message = $_GET['message'];

// If session id or receiver is empty, return false.
if ($session_id == '' || $receiver == '')
{
   OutputError('Session id and receiver have to be provided');
   exit(1);
}

// If message is empty, do nothing.
if ($message == '')
{
   exit(0);
}

// extract user id from session id
$query = "SELECT user_id FROM user_sessions WHERE session_id='" . mysql_real_escape_string($session_id) . "'";
$user_id = $db->SelectScalar($query);
if ($user_id == false)
{
   OutputError('Incorrect session id');
   exit(1);
}

// try to extract receiver id, if user with given name does not exist it will be created
$query = "SELECT id FROM users WHERE username='" . mysql_real_escape_string($receiver) . "'";
$receiver_id = $db->SelectScalar($query);
if ($receiver_id == false)
{
   // create new user
   $query = 'INSERT INTO users (username, created_by) VALUES (' . 
      "'" . mysql_real_escape_string($receiver) . "'," .
      $user_id . ')';
      
   $receiver_id = $db->Insert($query);
   if ($receiver_id == -1)
   {
      OutputError('Cannot create new user (receiver)');
      exit(1);
   }
}

// all information required should be known, insert new message
$query = 'INSERT INTO messages (from_user_id, to_user_id, message, create_time) VALUES (' .
   $user_id . ',' .
   $receiver_id . ',' .
   "'" . mysql_real_escape_string($message) . "'," .
   'FROM_UNIXTIME(' . time() . '))';
if ($db->Insert($query) == -1)
{
   // @TODO: create transation for whole action
   OutputError("Cannot add new message");
   exit(1);
}

require_once './common/footer.php';

?>